package com.cy.personer.web;


import com.cy.personer.util.ImageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Controller
@RequestMapping("/imageAction")
public class ImageHandler {
    private Map<String, Object> map;
    private InputStream imageStream;

    @RequestMapping("/imgCode.action")
    public void execute(HttpServletResponse response,HttpServletRequest request) {
        try {
            Map<String, BufferedImage> imageMap = ImageUtil.createImage();
            //得到验证码
            String keyCode = imageMap.keySet().iterator().next();
            //得到图片
            BufferedImage image = imageMap.get(keyCode);
            HttpSession session = request.getSession();
//            session.setAttribute("keyCode", keyCode.toLowerCase());
            session.setAttribute("keyCode", keyCode);
            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public InputStream getImageStream() {
        return imageStream;
    }

    public void setImageStream(InputStream imageStream) {
        this.imageStream = imageStream;
    }
}
